package com.tianyang.yukuaifu.common.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.AttributeSet;

import androidx.core.content.ContextCompat;

import com.tencent.smtt.export.external.interfaces.ConsoleMessage;
import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tianyang.yukuaifu.R;
import com.tianyang.yukuaifu.business.main.interfaces.IValueCallbackListener;
import com.tianyang.yukuaifu.common.interfaces.CommonConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Description：基于tencent的X5浏览器
 * Created by 薛勇军 on 2018/7/13.
 */

public class X5WebView extends WebView {

    public X5WebView(Context context) {
        super(context);
        setBackgroundColor(ContextCompat.getColor(context, R.color.c_f5f5f5));
    }

    private WebViewClient client = new WebViewClient() {
        /**
         * 防止加载网页时调起系统浏览器
         */
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    };

    @SuppressLint("SetJavaScriptEnabled")
    public X5WebView(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
        this.setWebViewClient(client);
        this.setWebChromeClient(new MyWebChromeClient());
        WebSettings webSetting = this.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(false);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSetting.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT > 21) {
            webSetting.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        this.getView().setClickable(true);
    }

    private IValueCallbackListener callbackListener;

    public void setValueCallbackListener(IValueCallbackListener callbackListener) {
        this.callbackListener = callbackListener;
    }

    private class MyWebChromeClient extends WebChromeClient {

        @Override
        public boolean onJsPrompt(WebView webView, String url, String message, String s2,
                                  JsPromptResult result) {
            if (callbackListener != null) {
                callbackListener.onJsPrompt(webView, url, message, s2, result);
            }
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            return true;
        }

        @Override
        public void onProgressChanged(WebView webView, int newProgress) {
            super.onProgressChanged(webView, newProgress);
            if (callbackListener != null) {
                callbackListener.onProgressChanged(webView, newProgress);
            }
        }

        // For Android 5.0+
        /*
          需加入混淆
         */
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
            if (callbackListener != null) {
                callbackListener.callback(null, valueCallback);
            }
            choosePicture();
            return true;
        }

        // Android > 4.1.1 调用这个方法
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            if (callbackListener != null) {
                callbackListener.callback(uploadMsg, null);
            }
            choosePicture();
        }

        // 3.0 + 调用这个方法
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType) {
            if (callbackListener != null) {
                callbackListener.callback(uploadMsg, null);
            }
            choosePicture();
        }

        // Android < 3.0 调用这个方法
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            if (callbackListener != null) {
                callbackListener.callback(uploadMsg, null);
            }
            choosePicture();
        }
    }

    private void choosePicture() {
        String cameraName = "a" + System.currentTimeMillis();
        String cameraDir = CommonConfig.DIR_APP_CACHE + "/";
        String cameraPath = CommonConfig.DIR_APP_CACHE + "/" + cameraName + ".jpg";

        File file = new File(cameraDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        Uri imageUri = Uri.fromFile(new File(cameraPath));
        if (callbackListener != null) {
            callbackListener.callback(imageUri);
        }
        final List<Intent> cameraIntents = new ArrayList<>();
        final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        final PackageManager packageManager = getContext().getPackageManager();
        final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for (ResolveInfo res : listCam) {
            final String packageName = res.activityInfo.packageName;
            final Intent i = new Intent(captureIntent);
            i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            i.setPackage(packageName);
            i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            cameraIntents.add(i);
        }
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Intent chooserIntent = Intent.createChooser(i, "拍照或选择照片");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
        ((Activity) getContext()).startActivityForResult(chooserIntent, CommonConfig.WEB_REQUESTCODE_FILE_CHOOSE);
    }
}
